package cn.edu.sjtu.rfa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLReaderAdapter;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.SearchManager;
import android.app.TimePickerDialog;
import android.appwidget.AppWidgetManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ContentProviderClient;
import android.content.ContentQueryMap;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.content.pm.PackageManager;
import android.content.res.AssetManager.AssetInputStream;
import android.content.res.Resources;
import android.database.Cursor;
import android.gesture.GesturePoint;
import android.gesture.GestureStroke;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.inputmethodservice.ExtractEditText;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.media.MediaScannerConnection;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.MailTo;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Parcel;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.text.Editable;
import android.util.AttributeSet;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;

import randoop.main.*;

public class RandoopForAndroidActivity extends Activity {
	
	public static Context rc = null;
	public static Camera camera = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        rc = this;

        final Button button_1 = (Button) findViewById(R.id.button_1);
        button_1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	String[] args = {"gentests", 
                		"--classlist=/data/class_1.txt", 
                		"--componentfile-txt=/data/seedSequence.txt",
                		"--literals-level=CLASS",
                		"--literals-file=/data/literals.txt",
                		"--log=/data/rLog.txt"};
            	//String[] args = {"gentests", "--testclass=android.app.Activity", "--literals-level=CLASS", "--literals-file=/data/literals.txt", "--forbid-null=false", "--log=/data/rLog.txt"};
            	List<String> arg = new ArrayList<String>();
            	Collections.addAll(arg, args);
            	EditText et = (EditText)findViewById(R.id.et);
            	if (!et.getText().toString().equals("")) {
                	String[] input = et.getText().toString().split(" ");
                	Collections.addAll(arg, input);
            	}
            	
            	String[] param = new String[arg.size()];
            	arg.toArray(param);
            	
                Main main = new Main();
                main.nonStaticMain(param);
            }
        });
    }
    
    public static Context getCurrentContext() {
    	if (rc == null) {
    		System.out.println("@@@ CurrentContext is null @@@");
    	}
    	return rc;
    }
    
    public static WifiManager getWifiManager() {
    	if (rc != null) {
    		System.out.println("@@@ Before get WifiManager @@@");
    		return (WifiManager) rc.getSystemService(Context.WIFI_SERVICE);
    	} else {
    		return null;
    	}
    }
    
    public static Parcel getParcel() {
    	return Parcel.obtain();
    }
    
    public static AccountManager getAccountManager() {
    	return AccountManager.get(rc);
    }
    
    public static ActivityManager getActivityManager() {
    	System.out.println("@@@ Before get ActivityManager @@@");
    	return (ActivityManager) rc.getSystemService(Context.ACTIVITY_SERVICE);
    }
    
    public static AppWidgetManager getAppWidgetManager() {
    	return AppWidgetManager.getInstance(rc);
    }
    
    public static BluetoothAdapter getBluetoothAdapter() {
    	return BluetoothAdapter.getDefaultAdapter();
    }
    
    // TODO
    public static BluetoothDevice getBluetoothDevice() {
    	return getBluetoothAdapter().getRemoteDevice("00:00:00:00:00:00");
    }
    
    public static BluetoothSocket getBluetoothSocket() throws IOException {
    	return getBluetoothDevice().createRfcommSocketToServiceRecord(UUID.randomUUID());
    }
    
    public static BluetoothServerSocket getBluetoothServerSocket() throws IOException {
    	return getBluetoothAdapter().listenUsingRfcommWithServiceRecord("SDP", UUID.randomUUID());
    }
    
    public static ScanResult getScanResult() {
    	WifiManager wifiMgr = (WifiManager) rc.getSystemService(Context.WIFI_SERVICE);
    	System.out.println("@@@ after get wifi manager @@@");
    	if(wifiMgr.isWifiEnabled()) {
    	  System.out.println("@@@ after check wifi enable @@@");
    	  List<ScanResult> scanResults = wifiMgr.getScanResults();
    	  if (scanResults != null && scanResults.size() > 0) {
    		  return scanResults.get(0);
    	  }
    	}
    	return null;
    }
    
    public static WifiInfo getWifiInfo() {
    	WifiManager wm = getWifiManager();
    	if (wm != null) {
    		return wm.getConnectionInfo();
    	}
    	return null; 
    }
    
    public static Editable.Factory getEditableFactory() {
		return Editable.Factory.getInstance();
    }
    
    public static Editable getEditable() {
		return getEditableFactory().newEditable("");
    }
    
    public static Intent getWebIntent() {
    	return new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
    }
    
    public static Intent getDialIntent() {
    	return new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0800000123"));
    }
    
    public static Intent getMMSIntent() {
    	return new Intent(Intent.ACTION_SEND, Uri.parse("content://media/external/images/media/23"));
    }
    
    public static Intent getSMSIntent() {
    	return new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto://0800000123"));
    }
    
    // TODO: can't get the instance without exception "Can't create handler inside thread that has not called Looper.prepare()"
    public static PhoneStateListener getPhoneStateListener() {
    	Looper.prepare();	// TODO can't close
    	return new PhoneStateListener();
    }
    
    public static CellLocation getGsmCellLocation() {
    	return new GsmCellLocation();
    }
    
    public static CellLocation getCdmaCellLocation() {
    	return new CdmaCellLocation();
    }
    
    public static Activity getActivity() {
    	return (Activity) rc;
    }
    
    public static String[] getLString() {
    	return new String[0];
    }
    
    public static RadioGroup getRadioGroup() {
    	return new RadioGroup(rc);
    }
    
    public static AttributeSet getAttributeSet() {
    	//XmlPullParser parser = Resources.getXml(myResouce);
    	AttributeSet attributes = Xml.asAttributeSet(null);
    	return null;//attributes;
    }
    
    public static File getFile() {
    	return new File("/data/temp.txt");
    }
    
    public static BufferedReader getBufferedReader() throws FileNotFoundException {
    	return new BufferedReader(new FileReader("/data/temp.txt"));
    }
    
    public static ContentHandler getContentHandler() throws SAXException {
    	return new XMLReaderAdapter();
    }
    
    public static MailTo getMailTo() {
    	return MailTo.parse("mailto:ybwebber@sjtu.edu.cn");
    }
    
    public static ConnectivityManager getConnectivityManager() {
    	return (ConnectivityManager) rc.getSystemService(Context.CONNECTIVITY_SERVICE);
    }
    
    public static Resources getResourcesHelper() {
    	return rc.getResources();
    }
    
    public static PackageManager getPackageManagerHelper() {
    	return rc.getPackageManager();
    }
    
    public static Uri getUri() {
    	return Uri.parse("content://telephony/carriers");
    }
    
    public static ContentResolver getContentResolverHelper() {
    	return rc.getContentResolver();
    }
    
    public static ContentProviderClient getContentProviderClient() {
    	return getContentResolverHelper().acquireContentProviderClient(getUri());
    }
    
    public static IntentFilter getIntentFilter() throws MalformedMimeTypeException {
    	return new IntentFilter(Intent.ACTION_VIEW, "vnd.android.cursor.dir/person");
    }
    
    public static ContentQueryMap getContentQueryMap() {
    	Cursor cur = rc.getContentResolver().query(Uri.parse("content://telephony/carriers"), null, null, null, null);
    	return new ContentQueryMap(cur, "_id", false, null);
    }
    
    public static Cursor getCursor() {
    	return rc.getContentResolver().query(Uri.parse("content://telephony/carriers"), null, null, null, null);
    }
    
    public static GestureStroke getGestureStroke() {
    	GesturePoint gp = new GesturePoint(0, 0, 0);
    	ArrayList<GesturePoint> ps = new ArrayList<GesturePoint>();
    	ps.add(gp);
    	return new GestureStroke(ps);
    }
    
    public static KeyguardManager getKeyguardManager() {
    	return (KeyguardManager) rc.getSystemService(Context.KEYGUARD_SERVICE);
    }
    
    public static Bitmap getBitmap() {
    	return Bitmap.createBitmap(1, 1, Config.ARGB_8888);
    }
    
    public static SearchManager getSearchManager() {
    	return (SearchManager) rc.getSystemService(Context.SEARCH_SERVICE);
    }
    
    public static TimePickerDialog getTimePickerDialog() {
    	return new TimePickerDialog(rc, null, 1, 1, false);
    }
    
    public static DatePickerDialog getDatePickerDialog() {
    	return new DatePickerDialog(rc, null, 1, 1, 1);
    }
    
    public static NotificationManager getNotificationManager() {
    	return (NotificationManager) rc.getSystemService(Context.NOTIFICATION_SERVICE);
    }
    
    public static AlarmManager getAlarmManager() {
    	return (AlarmManager) rc.getSystemService(Context.ALARM_SERVICE);
    }
    
    public static SensorManager getSensorManager() {
    	return (SensorManager) rc.getSystemService(Context.SENSOR_SERVICE);
    }
    
    public static Sensor getSensor() {
    	return getSensorManager().getSensorList(0).get(0);
    }
    
    public static Camera getCamera() {
    	if (camera == null) {
    		camera = Camera.open();
    	}
    	return camera;
    }
    
    public static Parameters getParameters() {
    	return getCamera().getParameters();
    }
    
    public static Keyboard getKeyboard() {
    	return new Keyboard(rc, R.xml.qwerty);
    }
    
    public static ExtractEditText getExtractEditText() {
    	return new ExtractEditText(rc);
    }
    
    public static Ringtone getRingtone() {
    	RingtoneManager rm = new RingtoneManager(rc);
    	return rm.getRingtone(0);
    }
    
    public static AudioTrack getAudioTrack() {
    	int bufsize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT);
    	return new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_DEFAULT, AudioFormat.ENCODING_PCM_16BIT, bufsize, AudioTrack.MODE_STREAM);
    }
    
    public static MediaScannerConnection getMediaScannerConnection() {
    	return new MediaScannerConnection(rc, null);
    }
    
    public static AudioRecord getAudioRecord() {
    	return new AudioRecord(MediaRecorder.AudioSource.MIC, 44100,  
    			AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, AudioRecord.getMinBufferSize(44100,  
    					AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT));  
    }
}